package com.keyholesoftware.trango.employee.controller;

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.keyholesoftware.trango.annotations.TrangoController;
import com.keyholesoftware.trango.employee.entity.Employee;
import com.keyholesoftware.trango.employee.service.EmployeeService;

@TrangoController(service = EmployeeService.class)
public class EmployeeController {

	@Autowired
	private EmployeeService employeeService;

	@RequestMapping(value = "/employee/create", method = RequestMethod.POST)
	public String createEmployee(Employee employee) {
		this.employeeService.persist(employee);
		return "redirect:/";
	}

	@RequestMapping(value = "/employee/delete/{identifier}", method = RequestMethod.GET)
	public String deleteEmployee(@PathVariable("identifier") Long identifier, ModelMap model) {
		Employee employee = this.employeeService.find(identifier);
		this.employeeService.remove(identifier, employee);
		return "redirect:/";
	}

	@RequestMapping(value = "/employee/list", method = RequestMethod.GET)
	public String list(ModelMap model) {
		List<Employee> employees = this.employeeService.findAll();
		model.addAttribute("employees", employees);
		return "list";
	}

	@RequestMapping(value = "/employee/list/json", method = RequestMethod.GET)
	public @ResponseBody
	String listJSON(ModelMap model) throws JsonGenerationException, JsonMappingException, IOException {
		List<Employee> employees = this.employeeService.findAll();
		model.addAttribute("employees", employees);
		ObjectMapper mapper = new ObjectMapper();
		StringWriter writer = new StringWriter();
		JsonGridData jsonGridData = new JsonGridData(1, 1, new Long(employees.size()), employees);
		mapper.writeValue(writer, jsonGridData);
		return writer.toString();
	}

	@RequestMapping(value = "/employee/create", method = RequestMethod.GET)
	public String showCreateForm(ModelMap model) {
		Employee employee = new Employee();
		model.addAttribute("employee", employee);
		return "create";
	}

	@RequestMapping(value = "/employee/{identifier}", method = RequestMethod.GET)
	public String showEmployee(@PathVariable("identifier") Long identifier, ModelMap model) {
		Employee employee = this.employeeService.find(identifier);
		model.addAttribute("employee", employee);
		return "index";
	}
}
